/**
 * 成长记录详情-教师、家长端
 * Created by xxx on 2017/7/13.
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'
import {
    HttpService,
    getLocalTime,
    Tips,
    AjaxUploadImgUrl,
    viewerImg,
    browser,
    getDefaultImg,
    iosfocus,
    iosblur,
    lazyLoad
} from '../Tools'
import Header from './Common/Header'
import ConfirmBox from './Common/ConfirmBox'
import lazyImg from '../Img/other/albumDefault.png';

export default class GrowthRecordDetails extends Component {
    constructor(props) {
        super(props);
        this.czjlid = this.props.params.id;
        // this.viewer = '';
        this.config = {
            title: '删除记录',
            content: '是否删除该条成长记录？',
            sureName: '删除'
        };
        this.state = {
            type: true, //true 学生 false 评论
            growthRecordDetails: [],
            show: 0,
            isTop: false,
            showMask: false
        }
    }
    // shouldComponentUpdate(nextProps, nextState) {
    //     return false
    // }

    componentWillMount() {
        if (this.props.params.iscomment == 'true')
            this.setState({
                type: false
            })
        this.getGrowthRecordDetails();
    }

    componentDidMount() {
        console.log(document.querySelector('.list_info'));
        //setTimeout(()=>{
        lazyLoad(document.querySelector('.showImg_div'));
        //},1000)
        if (document.querySelector('.transparent_mask'))
            document.querySelector('.transparent_mask').onmouseover = () => {
                if (sessionStorage.interval) {
                    clearInterval(sessionStorage.interval);
                    delete sessionStorage.interval
                }
                document.querySelector('#reply').blur();
                this.setState({
                    showMask: false
                });
            }
        // ;!function(pkg, undefined){ //此声明函数在xback.js文件里有，在app.js里必须再声明一次，不然监听返回事件失败
        //     let STATE = 'x-back';
        //     let element;
        //
        //     let onPopState = function(event){
        //         event.state === STATE && fire();
        //         record(STATE);  //初始化事件时，push一下
        //     };
        //
        //     let record = function(state){
        //         history.pushState(state, null, location.href);
        //     };
        //
        //     let fire = function(){
        //         let event = document.createEvent('Events');
        //         event.initEvent(STATE, false, false);
        //         element.dispatchEvent(event);
        //     };
        //
        //     let listen = function(listener){
        //         element.addEventListener(STATE, listener, false);
        //     };
        //
        //     !function(){
        //         element = document.createElement('span');
        //         window.addEventListener('popstate', onPopState);
        //         this.listen = listen;
        //         record(STATE);
        //         console.log(window[pkg])
        //     }.call(window[pkg] = window[pkg] || {});
        //
        // }('XBack');
        //
        // XBack.listen(function(){
        //     alert('oh! you press the back button');
        //     // hashHistory.go(-1);
        // });
        // XBack.listen(function(){
        //     alert('ah, press press press');
        // });

        // //学生和评论浮动在头部
        // window.onscroll = () => {
        //     if (document.body.scrollTop > document.querySelector('.content_list').offsetHeight) {
        //         this.setState({isTop: true});
        //     } else {
        //         this.setState({isTop: false});
        //     }
        // };
    }
    closeMask() {
        document.getElementById('reply').blur();
    }
    getGrowthRecordDetails() {
        HttpService.query({
            url: '/jxt-commonbackground/ajaxGrowup.do',
            data: {
                czjlid: this.czjlid,
                jybTicket: sessionStorage.ticket,
                method: 'ajaxJybJSON_003QryCzjlDetail'
            },
            async: false,
            success: (res => {
                if (res == null) {
                    Tips('该成长记录已被删除', 0);
                    return
                }
                if (res.code == 0) {
                    this.state.growthRecordDetails = [res.r];
                    this.setState({
                        growthRecordDetails: this.state.growthRecordDetails
                    });
                    return;
                }
                Tips(res.msg);
            })
        })
    }
    setType(type) {
        this.setState({
            type: type
        });
    }
    /**
     * 显示confirmBox
     */
    delete() {
        this.setState({
            show: 1
        })
    }

    /**
     * 关闭confirmBox
     */
    cfmCancel() {
        this.setState({
            show: 0
        });
    }

    /**
     * 确定
     * @returns {XML}
     */
    cfmSure() {
        //差加载动画
        HttpService.query({
            url: '/jxt-commonbackground/ajaxGrowup.do',
            data: {
                czjlid: this.czjlid,
                jybTicket: sessionStorage.ticket,
                method: 'ajaxJybJSON_103DeleteCzjl'
            },
            //async: false,
            success: (res => {
                if (res.code == 0) {
                    this.setState({
                        show: 0
                    });
                    Tips('删除成功！', 1);
                    // setTimeout(function() {
                    //
                    // }, 1000)
                    hashHistory.goBack(-1);
                } else {
                    this.setState({
                        show: 0
                    });
                    Tips(res.msg);
                }
            })
        })
    }

    /**
     * 评论
     */
    reply() {
        let reply = document.getElementById('reply').value;
        if (reply == '') {
            Tips('评论内容不能为空！');
            return;
        } else if (reply.indexOf('%') > -1) {
            Tips('评论内容不能为包含"%"！');
            return;
        }
        HttpService.query({
            url: '/jxt-commonbackground/ajaxGrowup.do',
            data: {
                czjlid: this.czjlid,
                replaycontent: reply,
                jybTicket: sessionStorage.ticket,
                method: 'ajaxJybJSON_102AddCzjlReplay'
            },
            //async: false,
            success: (res => {
                if (res.code == 0) {
                    Tips('评论成功！', 1);
                    this.setState({
                        type: false
                    });
                    this.getGrowthRecordDetails();
                    document.getElementById('reply').value = '';
                } else {
                    Tips(res.msg);
                }
            })
        })
    }

    /**
     * 点击评论输入框
     * onFocus={this.replyContentFocus.bind(this)}
     * @returns {XML}
     */
    replyContentFocus() {
        this.setState({
            showMask: true
        });
        iosfocus()
    }
    replyContentBlur() {
        iosblur()
        this.setState({
            showMask: false
        });
    }
    render() {
        let growthRecordDetailsData = this.state.growthRecordDetails;
        if (growthRecordDetailsData.length == 0)
            return <Header title='成长记录'/>
        const growthRecordList = growthRecordDetailsData.map((item, index) => {
            return (
                <div className="content_list">
                    <img src={getDefaultImg()} className="list_header_img"/>
                    <div className="list_info">
                        <span className="username" style={{background:'none'}}>{item.username}</span>
                        <span className="content">{item.content}</span>
                        {item.uploadfilepic != null
                            ? <div className="showImg_div"  style={{backgroundImage:'url('+AjaxUploadImgUrl + item.uploadfilepic+')'}}><img className="showImg" onClick={viewerImg.bind(this,'data-viewer')} src={lazyImg}  data-src={AjaxUploadImgUrl + item.uploadfilepic} data-viewer={AjaxUploadImgUrl + item.uploadfilepic} /></div>
                            : ''
                        }
                        <span className="time">{getLocalTime(item.zzCreateDate)}</span>
                    </div>
                </div>
            )
        });
        const headerLink = <a className='h_link delete_red' onClick={this.delete.bind(this)}/>;
        const studentList = growthRecordDetailsData[0].toStudents.split(',').map((item, index) => {
            return (
                <li>{item}</li>
            )
        });
        const replyList = growthRecordDetailsData[0].replays.map((item, index) => {
            const timeStr = getLocalTime(item.replayDate);
            return (
                <li>
                    <img src={getDefaultImg()}/>
                    <div className="reply_info">
                        <span className="people clearfix">{item.username}
                            <span className="time">{timeStr}</span>
                        </span>
                        <span className="reply_content">{item.replayContent}</span>
                    </div>
                </li>
            )
        });
        const {
            type,
            isTop,
            showMask,
            show
        } = this.state
        return (
            <div className='growth_record_details_page'>
                {/*<div style={{display:showMask == false?'none':'block'}} className="transparent_mask" ></div>*/}
                <Header title='成长记录' link={headerLink}/> {growthRecordList}
                <div className="details_content">
                    <div className={isTop == true
                        ? 'type_list top'
                        : 'type_list '}>
                        <div className={type == true
                            ? 'select'
                            : ''} onClick={this.setType.bind(this, true)}>学生({growthRecordDetailsData[0].toStudents.split(',').length})</div>
                        <div className={type == true
                            ? ''
                            : 'select'} onClick={this.setType.bind(this, false)}>评论({growthRecordDetailsData[0].replays.length})</div>
                    </div>
                    {type == true
                        ? <div className="student_list clearfix">
                            <ul>
                                {studentList == ''
                                    ? <p>没有学生</p>
                                    : studentList}
                            </ul>
                        </div>
                        : <div className="reply_list">
                            <ul>
                                {replyList == ''
                                    ? <p>没有评论</p>
                                    : replyList}
                            </ul>
                        </div>
                    }
                </div>
                <div className='mask' style={{display:showMask == false?'none':'block'}} onClick={this.closeMask.bind(this)} />
                <div className="reply">
                    <div className="content"><input type="text" id="reply" placeholder="说点什么" onBlur={this.replyContentBlur.bind(this)} onFocus={this.replyContentFocus.bind(this)} maxLength='50'/></div>
                    <div className="button"><input type="submit" value='评论' onTouchStart={this.reply.bind(this)}/></div>
                </div>
                <ConfirmBox config={this.config} show={show} cancel={this.cfmCancel.bind(this)} sure={this.cfmSure.bind(this)}/>
            </div>
        )
    }
}
